﻿namespace DotNetCRM.Core.ExtensionMethods
{
    /// <summary>
    /// Extensions for decimals
    /// </summary>
    public static class DecimalExtensions
    {
        /// <summary>
        /// Calculates the scale required to show the significant digits
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public static int CalculateScale(this decimal parm)
        {
            string s = parm.ToString("G29");
            int dotIndex = s.IndexOf('.');
            int scale = 0;
            if (dotIndex >= 0)
            {
                scale = s.Length - (dotIndex + 1);
            }
            return scale;
        }

        /// <summary>
        /// Calculates the scale required to show the significant digits
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public static int CalculateScale(this decimal? parm)
        {
            int scale = 0;
            if (parm.HasValue)
            {
                scale = parm.Value.CalculateScale();
            }
            return scale;
        }

        /// <summary>
        /// Central function for decimal ToString formatting
        /// </summary>
        /// <param name="parm">decmal? to format</param>
        /// <returns>formatted decimal string</returns>
        public static string ToFormattedString(this decimal? parm)
        {
            string val = "0";
            if (parm.HasValue)
            {
                val = parm.Value.ToFormattedString();
            }
            return val;
        }

        /// <summary>
        /// Central function for decimal ToString formatting
        /// </summary>
        /// <param name="parm">decmal to format</param>
        /// <returns>formatted decimal string</returns>
        public static string ToFormattedString(this decimal parm)
        {
            return parm.ToString("G29");
        }
    }
}